package cn.wizzer.app.web.commons.ext.websocket.monitor;

import cn.wizzer.app.match.modules.models.constant.RedisKey;
import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.web.commons.ext.websocket.main.monitor.BaseNettyMonitor;
import cn.wizzer.app.web.commons.ext.websocket.main.monitor.NettyMonitor;
import cn.wizzer.app.web.commons.utils.NettyMsgUtil;
import cn.wizzer.app.web.commons.utils.RedisUtil;
import cn.wizzer.framework.util.JSONUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;

import java.util.HashSet;

import static cn.wizzer.app.user.modules.models.constant.ChatConstant.*;

@IocBean
@NettyMonitor(order = 1)
public class LiveNettyMonitor extends BaseNettyMonitor {

    @Override
    public void added(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();


        //region 聊天方面初始化方法
        NutMap user = new NutMap()
                .addv("id", incoming.id().toString())
                .addv("nickName", incoming.id().toString())
                .addv("headPicture", "")
                .addv("roomManager", false)
                .addv("sessionDisabled", false)
                .addv("manageRoom", new HashSet<String>())
                .addv("channelId", incoming.id().toString())
                .addv("roomId", DEFAULT);
        RedisUtil.hset(CHAT_USER, incoming.id().toString(), user);

        NettyMsgUtil.joinRoom(incoming, JSONUtil.parseJavaBean(User.class, user), DEFAULT);
        //endregion
    }

    @Override
    public void removed(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();
        String originRoom = RedisUtil.hget(User.class, CHAT_USER, incoming.id().toString()).getRoomId();
        //清除用户信息
        RedisUtil.hdel(CHAT_USER, incoming.id().toString());
        NettyMsgUtil.leaveRoom(incoming, originRoom);
        // 当直播结束并聊天室人数为零->销毁channelGroup
        String liveInfo = RedisUtil.hget(RedisKey.KEY_LIVE, originRoom);
        ChannelGroup liveRoomChannels = NettyMsgUtil.getLiveRoomChannels(originRoom, incoming);
        if (liveRoomChannels.size() == 0 && !originRoom.equals(DEFAULT)) {
            liveRoomChannels.close();
            RedisUtil.del(CHAT_ROOM + originRoom);
        }
    }
}
